package com.zhugang.week07;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @program algorithms
 * @description: listOfDepth
 * @author: chanzhugang
 * @create: 2022/07/28 10:21
 */
public class ListOfDepth {

    /**
     * 面试题04.03 特定深度节点链表
     *
     * @param tree
     * @return
     */
    public ListNode[] listOfDepth(TreeNode tree) {
        // 每一层的元素转成链表，返回链表数组
        // 层序遍历：队列
        List<ListNode> result = new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(tree);
        while (!queue.isEmpty()) {
            ListNode dummyHead = new ListNode();
            ListNode tail = dummyHead;
            int curLevelNum = queue.size();
            for (int i = 0; i < curLevelNum; i++) {
                TreeNode node = queue.poll();
                tail.next = new ListNode(node.val);
                tail = tail.next;
                if (node.left != null) {
                    queue.add(node.left);
                }
                if (node.right != null) {
                    queue.add(node.right);
                }
            }
            result.add(dummyHead.next);
        }
        // list to array
        ListNode[] resultArr = result.stream().toArray(ListNode[]::new);
        return resultArr;
    }

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }


    public class ListNode {
        int val;
        ListNode next;

        public ListNode() {
        }

        ListNode(int x) {
            val = x;
        }
    }
}